<template>
  <div class="serial-manager">
    <button @click="handleRequestPort" :disabled="port">
      {{ port ? '已选择端口' : '选择串口设备' }}
    </button>
    <span v-if="port">✔ 已选择设备</span>

    <div v-if="port" class="controls">
      <label>波特率：
        <select v-model="baudRate">
          <option v-for="b in [9600, 19200, 38400, 57600, 115200]" :key="b" :value="b">
            {{ b }}
          </option>
        </select>
      </label>
      <button @click="handleOpenPort" :disabled="isOpen">
        {{ isOpen ? '已打开' : '打开串口' }}
      </button>
      <button @click="handleClosePort" :disabled="!isOpen">
        关闭串口
      </button>
      <span v-if="isOpen" class="status">✔ 串口已打开</span>
    </div>
  </div>
  
  <mydialog v-if='dialogFlag' :title="'Error'" :content="content" @close="dialogFlag = false" ></mydialog>
</template>

<script setup>
import { ref } from 'vue';
import serialService from '../services/serialService';
import mydialog from './mydialog.vue'


const dialogFlag = ref(false)
const content = ref('')

const port = ref(null);
const isOpen = ref(false);
const baudRate = ref(9600);

const dialogHanlder = (typeTitle,err)=>{
	dialogFlag.value = true
	content.value = typeTitle + err.message
}

// 定义可触发的事件
const emit = defineEmits(['status-change']);

// 1. 请求选择端口
async function handleRequestPort() {
  try {
    const selected = await serialService.requestPort();
    port.value = selected;
  } catch (err) {
	 dialogHanlder("打开串口失败：",err)
  }
}

// 2. 打开串口
async function handleOpenPort() {
  try {
    await serialService.openPort({ baudRate: baudRate.value });
    isOpen.value = true;
	emit('status-change', isOpen);
  } catch (err) {
    dialogHanlder("打开串口失败：",err)
  }
}

// 3. 关闭串口
async function handleClosePort() {
  try {
    await serialService.closePort();
    isOpen.value = false;
    port.value = null;
	emit('status-change', isOpen);
  } catch (err) {
    dialogHanlder("关闭串口失败：",err)
  }
}
</script>

<style scoped>
.serial-manager {
  margin: 16px 0;
}
.controls {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 12px;
}
.status {
  color: #4caf50;
  font-weight: bold;
}
button {
  padding: 6px 12px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
button:disabled {
  background: #ccc;
  cursor: not-allowed;
}
select {
  margin-left: 4px;
  padding: 4px;
}
</style>